package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Pan Rundong
 * @Date 2023-02-25 19:22
 * @Desc token拦截器
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    /**
     * Token鉴权
     *   成功：线程存入用户id以及Phone
     *   失败：抛出401异常
     * @Author: Pan Rundong
     * @param request
     * @param response
     * @param handler
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("Authorization");

        //2.通过token工具类鉴权
        boolean flag = JwtUtils.verifyToken(token);

        //3.不合格，报错并抛出异常
        if (!flag) {
            response.setStatus(401);
            return false;
        }

        //4. 合格，通过并将用户信息存入线程
            //4.1 从token中获取信息
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("id");
        String phone = (String) claims.get("phone");
            //4.2 存入User对象，并存入线程
        User user = new User();
        user.setId(Long.valueOf(userId));
        user.setMobile(phone);
        UserThreadLocal.setThreadLocal(user);

        //5.0 放行
        return true;
    }

    /**
     * 清除线程中信息
     * @Author: Pan Rundong
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return void
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
